package org.nerve.bigFileIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * org.nerve.bigFileIO
 * Created by zengxm on 2016/8/23.
 */
public class BigFileReader {
	protected Logger logger= LoggerFactory.getLogger(BigFileReader.class);

	/**
	 * 读取文件的前n行
	 * @param filepath
	 * @param n
	 * @return
	 */
	public List<String> getHead(String filepath, int n) throws IOException {
		File file = new File(filepath);

		List<String> lines=new ArrayList<>();
		try(
				FileInputStream fis=new FileInputStream(file);
				BufferedInputStream bis = new BufferedInputStream(fis);
				BufferedReader reader = new BufferedReader(new InputStreamReader(bis,"utf-8"),5*1024*1024)// 用5M的缓冲读取文本文件
				){
			String line;
			while((line = reader.readLine()) != null){
				lines.add(line);
				if(lines.size()>=n)
					break;
			}
		}catch (IOException e){
			e.printStackTrace();
		}

		return lines;
	}

	/**
	 * 获取文件的前几行，然后写入指定文件中
	 * @param filePath
	 * @param n
	 * @param out
	 */
	public void getHeadAndSaveTo(String filePath,int n,String out){
		long lc=0;
		try(
				FileWriter fileWriter=new FileWriter(out);
				BufferedWriter writer=new BufferedWriter(fileWriter);
				) {
			List<String> lines=getHead(filePath, n);
			System.out.println("read "+lines.size()+" from "+filePath);
			logger.debug("read "+lines.size()+" from "+filePath);
			for (String line : lines) {
				writer.write(line);
				writer.newLine();
				lc++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("write "+lc+" lines to "+out);
		logger.debug("write "+lc+" lines to "+out);
	}
}
